import React from "react";
import { createBrowserRouter, Navigate, useNavigate } from "react-router-dom";
import AdminLayout from "../layouts/AdminLayout";
import StudentLayout from "../layouts/StudentLayout";
import TeacherLayout from "../layouts/TeacherLayout";
import AdminHome from "../pages/admin/Home";
import TeacherManagement from "../pages/admin/Teachers";
import StudentManagement from "../pages/admin/Students";
import CourseManagement from "../pages/admin/Courses";
import DiscussionManagement from "../pages/admin/Discussion";
import StudentHome from "../pages/student/Home";
import StudentCourses from "../pages/student/Courses";
import StudentDiscussion from "../pages/student/Discussion";
import TeacherHome from "../pages/teacher/Home";
import TeacherCourses from "../pages/teacher/Courses";
import TeacherDiscussion from "../pages/teacher/Discussion";
import Login from "../pages/Login";
import Register from "../pages/Register";
import { useUser } from "../contexts/UserContext";
import { Result, Button, message, Spin } from "antd";
import TeacherPreparation from "../pages/teacher/Preparation";
import TeacherClassManagement from "../pages/teacher/ClassManagement";
import TeacherExamGeneration from "../pages/teacher/ExamGeneration";
import TemplateManagement from "../pages/teacher/ExamGeneration/TemplateManagement";
import TeacherExamManagement from "../pages/teacher/ExamManagement";
import TeacherExamGrading from "../pages/teacher/ExamGrading";
import TeacherHomeworkGrading from "../pages/teacher/HomeworkGrading";
import TeacherAnalysis from "../pages/teacher/LearningAnalysis";
import TeacherResources from "../pages/teacher/Resources";
import StudentExams from "../pages/student/Exams";
import StudentHomework from "../pages/student/Homework";
import StudentResources from "../pages/student/Resources";
import StudentExamTaking from "../pages/student/ExamTaking";
import StudentLearningAnalysis from "../pages/student/LearningAnalysis";
import UserProfile from "../components/UserProfile";
import Settings from "../pages/Settings";
import Dashboard from "../pages/admin/Dashboard";
import AddCourse from "../pages/teacher/Courses/AddCourse";
import CourseDetail from "../pages/teacher/Courses/CourseDetail";
import APIStatus from "../pages/admin/APIStatus";
import AIMonitoring from "../pages/admin/AIMonitoring";
import StudentCourseDetail from "../pages/student/CourseDetail";
import MessageCenter from "../pages/Message/MessageCenter";

interface PrivateRouteProps {
  element: React.ReactElement;
  requiredRole?: "admin" | "teacher" | "student";
}

const SmartHomeButton: React.FC = () => {
  const { user, isAuthenticated } = useUser();

  const handleGoHome = () => {
    if (isAuthenticated && user) {
      switch (user.role) {
        case "admin":
          window.location.href = "/admin";
          break;
        case "teacher":
          window.location.href = "/teacher";
          break;
        case "student":
          window.location.href = "/student";
          break;
        default:
          window.location.href = "/login";
      }
    } else {
      window.location.href = "/login";
    }
  };

  return (
    <Button type="primary" onClick={handleGoHome}>
      {isAuthenticated ? "返回首页" : "前往登录"}
    </Button>
  );
};

const ErrorBoundary: React.FC = () => {
  const navigate = useNavigate();
  const { user } = useUser();

  const getHomeRoute = () => {
    if (!user) return "/login";
    switch (user.role) {
      case "admin":
        return "/admin";
      case "teacher":
        return "/teacher";
      case "student":
        return "/student";
      default:
        return "/login";
    }
  };

  return (
    <Result
      status="500"
      title="系统错误"
      subTitle="抱歉，系统出现了一些问题。"
      extra={[
        <Button
          type="primary"
          key="home"
          onClick={() => navigate(getHomeRoute())}
        >
          返回首页
        </Button>,
        <Button key="retry" onClick={() => window.location.reload()}>
          重新加载
        </Button>,
      ]}
    />
  );
};

const PrivateRoute: React.FC<PrivateRouteProps> = ({
  element,
  requiredRole,
}) => {
  const { user, loading } = useUser();
  const navigate = useNavigate();

  React.useEffect(() => {
    if (!loading && !user) {
      message.error("请先登录");
      navigate("/login", { replace: true });
    } else if (!loading && requiredRole && user?.role !== requiredRole) {
      message.error("您没有权限访问该页面");
      navigate("/", { replace: true });
    }
  }, [loading, user, navigate, requiredRole]);

  if (loading) {
    return (
      <div
        style={{
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          height: "100vh",
        }}
      >
        <Spin size="large" tip="加载中..." />
      </div>
    );
  }

  if (!user) {
    return <Navigate to="/login" replace />;
  }

  if (requiredRole && user.role !== requiredRole) {
    return (
      <Result
        status="403"
        title="无权访问"
        subTitle="抱歉，您没有权限访问该页面"
        extra={
          <Button type="primary" onClick={() => navigate("/")}>
            返回首页
          </Button>
        }
      />
    );
  }

  return element;
};

const router = createBrowserRouter([
  {
    path: "/",
    element: <Navigate to="/login" replace />,
    errorElement: <ErrorBoundary />,
  },
  {
    path: "/login",
    element: <Login />,
    errorElement: <ErrorBoundary />,
  },
  {
    path: "/register",
    element: <Register />,
    errorElement: <ErrorBoundary />,
  },
  {
    path: "/admin",
    element: <PrivateRoute element={<AdminLayout />} requiredRole="admin" />,
    errorElement: <ErrorBoundary />,
    children: [
      {
        path: "",
        element: <AdminHome />,
      },
      {
        path: "home",
        element: <AdminHome />,
      },
      {
        path: "dashboard",
        element: <Dashboard />,
      },
      {
        path: "profile",
        element: <UserProfile />,
      },
      {
        path: "teachers",
        element: <TeacherManagement />,
      },
      {
        path: "students",
        element: <StudentManagement />,
      },
      {
        path: "courses",
        element: <CourseManagement />,
      },
      {
        path: "discussions",
        element: <DiscussionManagement />,
      },
      {
        path: "settings",
        element: <Settings />,
      },
      {
        path: "api-status",
        element: <APIStatus />,
      },
      {
        path: "ai-monitoring",
        element: <AIMonitoring />,
      },
      {
        path: "message",
        element: <MessageCenter />,
      },
    ],
  },
  {
    path: "/teacher",
    element: (
      <PrivateRoute element={<TeacherLayout />} requiredRole="teacher" />
    ),
    errorElement: <ErrorBoundary />,
    children: [
      {
        path: "",
        element: <TeacherHome />,
      },
      {
        path: "home",
        element: <TeacherHome />,
      },
      {
        path: "profile",
        element: <UserProfile />,
      },
      {
        path: "courses",
        element: <TeacherCourses />,
      },
      {
        path: "courses/add",
        element: <AddCourse />,
      },
      {
        path: "courses/:courseId",
        element: <CourseDetail />,
      },
      {
        path: "preparation",
        element: <TeacherPreparation />,
      },
      {
        path: "class-management",
        element: <TeacherClassManagement />,
      },
      {
        path: "exam-generation",
        element: <TeacherExamGeneration />,
      },
      {
        path: "exam-generation/templates",
        element: <TemplateManagement />,
      },
      {
        path: "exam-management",
        element: <TeacherExamManagement />,
      },
      {
        path: "exam-grading",
        element: <TeacherExamGrading />,
      },
      {
        path: "homework-grading",
        element: <TeacherHomeworkGrading />,
      },
      {
        path: "analysis",
        element: <TeacherAnalysis />,
      },
      {
        path: "learning-analysis",
        element: <TeacherAnalysis />,
      },
      {
        path: "resources",
        element: <TeacherResources />,
      },
      {
        path: "discussions",
        element: <TeacherDiscussion />,
      },
      {
        path: "settings",
        element: <Settings />,
      },
      {
        path: "message",
        element: <MessageCenter />,
      },
    ],
  },
  {
    path: "/student",
    element: (
      <PrivateRoute element={<StudentLayout />} requiredRole="student" />
    ),
    errorElement: <ErrorBoundary />,
    children: [
      {
        path: "",
        element: <StudentHome />,
      },
      {
        path: "home",
        element: <StudentHome />,
      },
      {
        path: "profile",
        element: <UserProfile />,
      },
      {
        path: "courses",
        element: <StudentCourses />,
      },
      {
        path: "homework",
        element: <StudentHomework />,
      },
      {
        path: "exams",
        element: <StudentExams />,
      },
      {
        path: "exam-taking/:examId?",
        element: <StudentExamTaking />,
      },
      {
        path: "learning-analysis",
        element: <StudentLearningAnalysis />,
      },
      {
        path: "resources",
        element: <StudentResources />,
      },
      {
        path: "discussions",
        element: <StudentDiscussion />,
      },
      {
        path: "settings",
        element: <Settings />,
      },
      {
        path: "course-detail/:courseId",
        element: <StudentCourseDetail />,
      },
      {
        path: "message",
        element: <MessageCenter />,
      },
    ],
  },
  {
    path: "*",
    element: (
      <Result
        status="404"
        title="404"
        subTitle="抱歉，您访问的页面不存在。"
        extra={<SmartHomeButton />}
      />
    ),
  },
]);

export { router };
